package node.block;

import grammar.Lexer;
import grammar.MyError;
import lexical.Key;
import lexical.Word;
import node.Node;
import node.block.stmt.AssignStmt;
import node.block.stmt.BreakStmt;
import node.block.stmt.ContinueStmt;
import node.block.stmt.GetintStmt;
import node.block.stmt.IfStmt;
import node.block.stmt.PrintStmt;
import node.block.stmt.ReturnStmt;
import node.block.stmt.WhileStmt;
import node.exp.Cond;
import node.exp.Exp;
import node.exp.LVal;
import symbol.Function;
import symbol.SymbolTable;

import java.util.ArrayList;
import java.util.Objects;

public class Stmt implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    public Node stmt;
    private final ArrayList<Node> nodes = new ArrayList<>();

    public Stmt(Lexer lexer, SymbolTable table, Node father) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        parseStmt();
    }

    private void parseStmt() {
        if (lexer.isWordType(0, Key.IFTK)) {
            parseIfStmt();
        } else if (lexer.isWordType(0, Key.WHILETK)) {
            parseWhileStmt();
        } else if (lexer.isWordType(0, Key.BREAKTK) || lexer.isWordType(0, Key.CONTINUETK)) {
            parseBreakContinueStmt();
        } else if (lexer.isWordType(0, Key.RETURNTK)) {
            parseReturnStmt();
        } else if (lexer.isWordType(0, Key.PRINTFTK)) {
            parsePrintStmt();
        } else if (lexer.isWordType(0, Key.LBRACE)) {
            Block block = new Block(lexer, table, this);
            nodes.add(block);
            stmt = block;
        } else {
            if (lexer.isWordType(0, Key.SEMICN)) {
                nodes.add(lexer.getCurWord()); // ;
                return;
            }
            int old = lexer.pos;
            Exp exp = new Exp(lexer, table, this);
            if (lexer.isWordType(0, Key.ASSIGN)) {
                lexer.pos = old;
                Word word = lexer.getWord(0);
                if (table.isSymbolConst(word.word)) {
                    lexer.addError(new MyError(word.lineNum, 'h'));
                }
                LVal lVal = new LVal(lexer, table, this);
                nodes.add(lVal);
                nodes.add(lexer.getCurWord()); // =
                if (lexer.isWordType(0, Key.GETINTTK)) {
                    nodes.add(lexer.getCurWord()); // getint
                    nodes.add(lexer.getCurWord()); // (
                    if (lexer.isWordType(0, Key.RPARENT)) {
                        nodes.add(lexer.getCurWord()); // )
                    } else {
                        lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'j'));
                    }
                    stmt = new GetintStmt(lVal);
                } else {
                    exp = new Exp(lexer, table, this);
                    nodes.add(exp);
                    stmt = new AssignStmt(exp, lVal);
                }
            } else {
                nodes.add(exp);
                stmt = exp;
            }
            if (lexer.isWordType(0, Key.SEMICN)) {
                nodes.add(lexer.getCurWord()); // ;
            } else {
                lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'i'));
            }
        }
    }

    private void parseIfStmt() {
        nodes.add(lexer.getCurWord()); // if
        nodes.add(lexer.getCurWord()); // (
        Cond cond = new Cond(lexer, table);
        nodes.add(cond);
        if (lexer.isWordType(0, Key.RPARENT)) {
            nodes.add(lexer.getCurWord()); // )
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'j'));
        }
        table.addSymbolBlock();
        Node ifStmt = new Stmt(lexer, table, this);
        nodes.add(ifStmt);
        table.subSymbolBlock(0);
        stmt = new IfStmt(cond, ifStmt);
        if (lexer.isWordType(0, Key.ELSETK)) {
            nodes.add(lexer.getCurWord()); // else
            table.addSymbolBlock();
            Node elseStmt = new Stmt(lexer, table, this);
            nodes.add(elseStmt);
            ((IfStmt)stmt).setElseStmt(elseStmt);
            table.subSymbolBlock(0);
        }
    }

    private void parseWhileStmt() {
        nodes.add(lexer.getCurWord()); // while
        nodes.add(lexer.getCurWord()); // (
        Cond cond = new Cond(lexer, table);
        nodes.add(cond);
        if (lexer.isWordType(0, Key.RPARENT)) {
            nodes.add(lexer.getCurWord()); // )
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'j'));
        }
        lexer.addWhileDeep();
        table.addSymbolBlock();
        Node whileStmt = new Stmt(lexer, table, this);
        nodes.add(whileStmt);
        table.subSymbolBlock(0);
        lexer.subWhileDeep();
        stmt = new WhileStmt(whileStmt, cond);
    }

    private void parseBreakContinueStmt() {
        if (lexer.whileDeep == 0) {
            lexer.addError(new MyError(lexer.getWord(0).lineNum, 'm'));
        }
        if (lexer.isWordType(0, Key.BREAKTK)) {
            stmt = new BreakStmt(this);
        } else {
            stmt = new ContinueStmt(this);
        }
        nodes.add(lexer.getCurWord()); // break | continue
        if (lexer.isWordType(0, Key.SEMICN)) {
            nodes.add(lexer.getCurWord()); // ;
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'i'));
        }
    }

    private void parseReturnStmt() {
        Function function = table.functions.get(table.functions.size() - 1);
        Exp exp = null;
        Word word = lexer.getWord(0);
        nodes.add(lexer.getCurWord()); // return
        if (!lexer.isWordType(0, Key.SEMICN) && !lexer.isWordType(0, Key.CONSTTK) &&
                !lexer.isWordType(0, Key.RBRACE) && !lexer.isWordType(0, Key.LBRACE) &&
                !lexer.isWordType(0, Key.IFTK) && !lexer.isWordType(0, Key.ELSETK) &&
                !lexer.isWordType(0, Key.BREAKTK) && !lexer.isWordType(0, Key.CONTINUETK) &&
                !lexer.isWordType(0, Key.RETURNTK) && !lexer.isWordType(0, Key.PRINTFTK) &&
                !lexer.isWordType(0, Key.WHILETK)) {
            if (Objects.equals(function.returnType, "void")) {
                lexer.addError(new MyError(word.lineNum, 'f'));
            }
            exp = new Exp(lexer, table, this);
            nodes.add(exp);
        }
        if (lexer.isWordType(1, Key.RBRACE) || lexer.isWordType(0, Key.RBRACE)) {
            table.addFunctionReturn();
        }
        if (lexer.isWordType(0, Key.SEMICN)) {
            nodes.add(lexer.getCurWord()); // ;
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'i'));
        }
        stmt = new ReturnStmt(exp, function);
    }

    private void parsePrintStmt() {
        Word printf = lexer.getWord(0);
        nodes.add(lexer.getCurWord()); // printf
        nodes.add(lexer.getCurWord()); // (
        Word strcon = lexer.getWord(0);
        nodes.add(lexer.getCurWord()); // strcon
        int numParam = 0;
        boolean errorA = false;
        for (int i = 1; i < strcon.word.length()-1; i++) {
            if (strcon.word.charAt(i) == '%' && strcon.word.charAt(i+1) == 'd') {
                numParam++;
                continue;
            }
            if ((strcon.word.charAt(i) == '\\' && strcon.word.charAt(i+1) != 'n') ||
                    !(strcon.word.charAt(i) == 32 || strcon.word.charAt(i) == 33 || (strcon.word.charAt(i) >= 40 && strcon.word.charAt(i) <= 126))) {
                errorA = true;
            }
        }
        if (errorA) {
            lexer.addError(new MyError(strcon.lineNum, 'a'));
        }
        ArrayList<Exp> exps = new ArrayList<>();
        while (lexer.isWordType(0, Key.COMMA)) {
            nodes.add(lexer.getCurWord()); // ,
            Exp exp = new Exp(lexer, table, this);
            nodes.add(exp);
            exps.add(exp);
        }
        if (numParam != exps.size()) {
            lexer.addError(new MyError(printf.lineNum, 'l'));
        }
        if (lexer.isWordType(0, Key.RPARENT)) {
            nodes.add(lexer.getCurWord()); // )
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'j'));
        }
        if (lexer.isWordType(0, Key.SEMICN)) {
            nodes.add(lexer.getCurWord()); // ;
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'i'));
        }
        stmt = new PrintStmt(strcon, exps);
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<Stmt>\n").toString();
    }

    @Override
    public String genMidCode() {
        if (stmt != null) {
            stmt.genMidCode();
        }
        return "";
    }
}

